<template>
    <a-row id="global-header" align="center" :wrap="false">
        <a-col flex="auto">
            <a-menu mode="horizontal" theme="dark" :selected-keys="selectedKey" @menu-item-click="handleMenuClick">
                <a-menu-item key="0" :style="{ padding: 0, marginRight: '38px' }" disabled>
                    <div class="titleBar">
                        <img class="logo" src="../assets/logo.svg" alt="logo" />
                        <div class="title">yuDaDa</div>
                    </div>
                </a-menu-item>
                <a-menu-item v-for="item in visibleRoutes" :key="item.path">{{ item.name }}</a-menu-item>
            </a-menu>
        </a-col>
        <a-col flex="100px" align="center">
            <div v-if="loginUserStore.loginUser.id">
                {{ loginUserStore.loginUser.userName ?? '无名' }}
            </div>
            <div v-else>
                <a-button type="primary" href="/user/login">Login</a-button>
            </div>
        </a-col>
    </a-row>

</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { routes } from '../router/route';
import { ref, computed } from 'vue';
import { useLoginUserStore } from "@/stores/userStore";
import checkAccess from '@/access/checkAccess';

const loginUserStore = useLoginUserStore();
const router = useRouter(); // 控制页面跳转

// 点击菜单，跳转到对应页面
const handleMenuClick = (key: string) => {
    router.push({
        path: key
    });
}

// 当前Tab选中的菜单项,需要定义响应式变量
const selectedKey = ref(["/"]);

// 路由跳转时，自动更新选中的菜单项
router.afterEach((to) => { // afterEach 是路由跳转后触发
    selectedKey.value = [to.path];
})

// 过滤掉菜单中想隐藏的路由
const visibleRoutes = computed(() => {
    return routes.filter((item) => {
        if (item.meta?.hideInMenu) {
            return false;
        }
        if (!checkAccess(loginUserStore.loginUser, item.meta?.access)) {
            return false;
        }
        return true;
    }); // ?.可选链操作符，hideInMenu为true时隐藏
});


</script>

<style scoped>
#global-header {
    box-sizing: border-box;
    width: 100%;
    /* padding: 40px; */
    background-color: var(--color-neutral-2);
}

.titleBar {
    display: flex;
    align-items: center;
}

.logo {
    width: 40px;
    height: 40px;
}

.title {
    margin-left: 10px;
    font-weight: 600;
    color: white
}
</style>